import { DialogWindow } from '../Dialog/DialogWindow'// CartoonCharacter.ts
export class CartoonCharacter {
    private container: HTMLElement;
    private character: SVGSVGElement;
    private leftEye: SVGElement;
    private rightEye: SVGElement;
    private leftEyebrow: SVGElement;
    private rightEyebrow: SVGElement;
    private mouth: SVGElement;
    private currentEmotion: string = 'normal';
    private talkingSet:boolean = false;
    // private isDragging = false;
    // private dragOffset = { x: 0, y: 0 };

  
    constructor() {
      this.container = document.createElement('div');
      this.initializeCharacter();
      this.setupEventListeners();
      // 添加事件监听
      // this.addEventListeners();
    }


    // private addEventListeners() {
    //   document.addEventListener('mousemove', this.handleMouseMove);
    // };

    // private handleMouseMove = (e: MouseEvent) => {
    //   console.log('动起来')
    //   if (this.isDragging) {
    //     const x = e.clientX - this.dragOffset.x;
    //     const y = e.clientY - this.dragOffset.y;
    //     this.container.style.left = `${x}px`;
    //     this.container.style.top = `${y}px`;
    //   }
    // }
    // private handleMouseUp = () => {
    //     this.isDragging = false;
    // };
  
    private initializeCharacter() {
      console.log('成功加载果小果');
      this.dialog('<h1>哈喽哈喽，下午好呀！</h1>', "烈焰杀神果小果")
      this.container.style.cssText = `
        position: fixed;
        right: 200px;
        bottom: 0px;
        width: 300px;
        height: 300px;
        z-index: 1000000;
        cursor: pointer;
        transform: all 0.3s ease-in-out;
      `;
      
      // 创建SVG角色
      this.character = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      this.character.setAttribute('viewBox', '0 0 300 300');
      this.character.style.width = '300px';
      this.character.style.height = '300px';
  
      // 背景（使用图片/imgs/gxg.png）
      const head = document.createElementNS('http://www.w3.org/2000/svg', 'image');
      head.setAttributeNS(null, 'href', 'imgs/gxg.png');
      head.setAttribute('x', '0');
      head.setAttribute('y', '0');
      head.setAttribute('width', '300');
      head.setAttribute('height', '300');
      // head.setAttribute('preserveAspectRatio', 'xMidYMid slice');
      // 头部
      /* const head = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
      head.setAttribute('cx', '100');
      head.setAttribute('cy', '100');
      head.setAttribute('r', '80');
      head.setAttribute('fill', '#FFD39B');
      head.setAttribute('stroke', '#000');
      head.setAttribute('stroke-width', '2'); */
  
      // 眼睛
      this.leftEye = this.createEye(87, 152, 'imgs/gxg/leftEye.png');
      this.rightEye = this.createEye(173, 152, 'imgs/gxg/rightEye.png');
  
      // 眉毛
      this.leftEyebrow = this.createEyebrow('M80,132 Q120,126 120,133');
      this.rightEyebrow = this.createEyebrow('M210,132 Q178,126 170,133');
  
      // 嘴巴
      this.mouth = this.createMouth();
  
      // 添加所有元素到SVG
      this.character.appendChild(head);
      this.character.appendChild(this.leftEyebrow);
      this.character.appendChild(this.rightEyebrow);
      this.character.appendChild(this.leftEye);
      this.character.appendChild(this.rightEye);
      this.character.appendChild(this.mouth);
  
      this.container.appendChild(this.character);
      document.body.appendChild(this.container);
      this.talking();
    }
  
    private createEye(x: number, y: number, img: string): SVGElement {
      const eyeGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
      
      // 眼白
      /* const eyeWhite = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
      eyeWhite.setAttribute('cx', x.toString());
      eyeWhite.setAttribute('cy', y.toString());
      eyeWhite.setAttribute('r', '15');
      eyeWhite.setAttribute('fill', 'white');
      eyeWhite.setAttribute('stroke', 'black');
      eyeWhite.setAttribute('stroke-width', '1'); */
  
      // 眼球
      // const pupil = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
      // pupil.setAttribute('cx', x.toString());
      // pupil.setAttribute('cy', y.toString());
      // pupil.setAttribute('r', '7');
      // pupil.setAttribute('fill', 'black');
      // 使用图片代替 (imgs/gxg/leftEye.png)
      const pupil = document.createElementNS('http://www.w3.org/2000/svg', 'image');
      pupil.setAttributeNS(null, 'href', img);
      pupil.setAttribute('x', x.toString());
      pupil.setAttribute('y', y.toString());
      pupil.setAttribute('r', '7');
      pupil.setAttribute('width', '38');
      pupil.setAttribute('height', '50');
  
      // eyeGroup.appendChild(eyeWhite);
      eyeGroup.appendChild(pupil);
      return eyeGroup;
    }
  
    // 创建眉毛
    private createEyebrow(position: string): SVGElement {
      // const eyebrow = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      // eyebrow.setAttribute('x1', x1.toString());
      // eyebrow.setAttribute('y1', y1.toString());
      // eyebrow.setAttribute('x2', x2.toString());
      // eyebrow.setAttribute('y2', y2.toString());
      // eyebrow.setAttribute('x3', x3.toString());
      // eyebrow.setAttribute('y3', y3.toString());
      // eyebrow.setAttribute('stroke', 'black');
      // eyebrow.setAttribute('stroke-width', '1');
      const eyebrow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      eyebrow.setAttribute('d', position);
      eyebrow.setAttribute('fill', 'none');
      eyebrow.setAttribute('stroke', '#211414');
      eyebrow.setAttribute('stroke-width', '1');
      return eyebrow;
    }
  
    // 创建嘴巴
    private createMouth(): SVGElement {
      const mouth = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      mouth.setAttribute('d', 'M142,215 Q152,220 160,215');
      mouth.setAttribute('fill', 'none');
      mouth.setAttribute('stroke', '#763309');
      mouth.setAttribute('stroke-width', '1');
      return mouth;
    }
  
    private setupEventListeners() {
      // 眼睛跟随鼠标
      document.addEventListener('mousemove', (e) => {
        this.updateEyePosition(e);
      });
  
      // 点击交互
      this.container.addEventListener('click', () => {
        this.cycleEmotions();
      });
  
      // 添加触摸支持
      this.container.addEventListener('touchstart', (e) => {
        e.preventDefault();
        this.cycleEmotions();
      });
    }
  
    private updateEyePosition(e: MouseEvent) {
      const rect = this.character.getBoundingClientRect();
      const centerX = rect.left + rect.width / 2;
      const centerY = rect.top + rect.height / 2;
  
      // 计算鼠标相对于角色中心的角度
      const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
      const distanceX = 2; // 眼球移动的最大距离
      const distanceY = 1;
  
      // 更新左眼位置
      const leftPupil = this.leftEye.querySelector('image');
      if (leftPupil) {
        const baseX = 87;
        const baseY = 152;
        // 设置图片位置
        leftPupil.setAttribute('x', (baseX + Math.cos(angle) * distanceX).toString());
        leftPupil.setAttribute('y', (baseY + Math.sin(angle) * distanceY).toString());
        // leftPupil.setAttribute('cx', (baseX + Math.cos(angle) * distance).toString());
        // leftPupil.setAttribute('cy', (baseY + Math.sin(angle) * distance).toString());
      }
  
      // 更新右眼位置
      const rightPupil = this.rightEye.querySelector('image');
      if (rightPupil) {
        const baseX = 173;
        const baseY = 152;
        rightPupil.setAttribute('x', (baseX + Math.cos(angle) * distanceX).toString());
        rightPupil.setAttribute('y', (baseY + Math.sin(angle) * distanceY).toString());

        // rightPupil.setAttribute('cx', (baseX + Math.cos(angle) * distance).toString());
        // rightPupil.setAttribute('cy', (baseY + Math.sin(angle) * distance).toString());
      }
    }
  
    private cycleEmotions() {
      const emotions = ['happy', 'sad', 'angry', 'surprised', 'normal','talking'];
      const currentIndex = emotions.indexOf(this.currentEmotion);
      const nextIndex = (currentIndex + 1) % emotions.length;
      this.setEmotion(emotions[nextIndex]);
    }
  
    public setEmotion(emotion: string) {
      this.currentEmotion = emotion;
      
      switch (emotion) {
        case 'happy':
          console.log('happy');
          this.dialog('你干嘛！', "烈焰杀神果小果")
          this.mouth.setAttribute('d', 'M142,215 Q152,220 160,215');
          this.mouth.setAttribute('fill', 'none');
          this.mouth.setAttribute('stroke-width', '1');
          this.leftEyebrow.setAttribute('transform', 'translate(0, -5)');
          this.rightEyebrow.setAttribute('transform', 'translate(0, -5)');
          break;
        case 'sad':
          console.log('sad');
          this.dialog('别打啦！别打啦，我知道错了！', "烈焰杀神果小果")
          this.mouth.setAttribute('d', 'M142,215 Q152,210 160,215');
          this.mouth.setAttribute('fill', 'none');
          this.mouth.setAttribute('stroke-width', '1');
          this.leftEyebrow.setAttribute('transform', 'translate(-20, 17) rotate(-10)');
          this.rightEyebrow.setAttribute('transform', 'translate(9, -20) rotate(5)');
          break;
        case 'angry':
          console.log('angry');
          this.dialog('你打吧~~！打死我好了！', "烈焰杀神果小果")
          this.mouth.setAttribute('d', 'M142,218 Q152,205 160,218');
          this.mouth.setAttribute('fill', 'none');
          this.mouth.setAttribute('stroke-width', '1');
          this.leftEyebrow.setAttribute('transform', 'translate(-20, 17) rotate(-10)');
          this.rightEyebrow.setAttribute('transform', 'translate(9, -20) rotate(5)');
          break;
        case 'surprised':
          console.log('surprised');
          this.dialog('我命由我不由天！！', "烈焰杀神果小果")
          this.mouth.setAttribute('d', 'M145,208 Q151,225 158,208');
          this.mouth.setAttribute('fill', 'none');
          this.mouth.setAttribute('stroke-width', '1');
          this.leftEyebrow.setAttribute('transform', 'translate(0, -10)');
          this.rightEyebrow.setAttribute('transform', 'translate(0, -10)');
          break;
        case 'talking':
          console.log('talking');
          this.mouth.setAttribute('d', 'M142,215 Q152,220 160,215');
          this.mouth.setAttribute('fill', '#763309');
          this.mouth.setAttribute('stroke-width', '1');
          
          this.leftEyebrow.setAttribute('transform', '');
          this.rightEyebrow.setAttribute('transform', '');
          break;
        default: // normal
          console.log('normal');
          this.mouth.setAttribute('d', 'M142,215 Q152,217 160,215');
          this.leftEyebrow.setAttribute('transform', '');
          this.rightEyebrow.setAttribute('transform', '');
          break;
      }
    }
    
    // 说话中嘴不停在动(talking与normal状态switch)
    
    public talking(value:boolean=true, isdo:boolean=false) {
      if(this.talkingSet){
        this.setEmotion('talking');
      }else{
        this.setEmotion('normal');
      }
      this.talkingSet = !value;
      
      if(isdo){return}
      setTimeout(() => {
        //  设置循环(1秒内循环5次)
        for (let i = 0; i < 5; i++) {
          setTimeout(() => {
            this.talking(this.talkingSet, true);
          }, 500);
        }
      }, 2000);
      
    }
  
    // 公共方法：设置位置
    public setPosition(position: { right?: number; bottom?: number }) {
      if (position.right !== undefined) {
        this.container.style.right = `${position.right}px`;
      }
      if (position.bottom !== undefined) {
        this.container.style.bottom = `${position.bottom}px`;
      }
    }
  
    // 公共方法：设置大小
    public setSize(size: number) {
      this.container.style.width = `${size}px`;
      this.container.style.height = `${size}px`;
    }
  
    // 销毁方法
    public destroy() {
      document.removeEventListener('mousemove', this.updateEyePosition);
      this.container.remove();
    }

    private dialog(msg="", title="", options: any={width:400, height:200}){
      const dlog = new DialogWindow({
        title: title,
        content: msg,
        width: options.width,
        height: options.height,
        closeOnOutsideClick: true
      })
      dlog.show()
    } 
  }